<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户注册 - Snapan</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
    }

    body {
      background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      padding: 20px;
    }

    .register-container {
      background-color: white;
      border-radius: 12px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
      width: 100%;
      max-width: 450px;
      padding: 40px 35px;
      position: relative;
      overflow: hidden;
      animation: fadeIn 0.5s ease-out;
    }

    .register-container::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 5px;
      background: linear-gradient(to right, #6a11cb, #2575fc);
    }

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(20px); }
      to { opacity: 1; transform: translateY(0); }
    }

    h1 {
      text-align: center;
      margin-bottom: 30px;
      color: #333;
      font-weight: 600;
      font-size: 28px;
    }


    .input-group {
      margin-bottom: 20px;
      position: relative;
    }

    label {
      display: block;
      margin-bottom: 8px;
      color: #555;
      font-weight: 500;
      font-size: 14px;
    }

    input[type="text"],
    input[type="email"],
    input[type="password"] {
      width: 100%;
      padding: 14px 15px;
      border: 1px solid #ddd;
      border-radius: 8px;
      font-size: 16px;
      transition: all 0.3s;
    }

    input[type="text"]:focus,
    input[type="email"]:focus,
    input[type="password"]:focus {
      border-color: #6a11cb;
      box-shadow: 0 0 0 2px rgba(106, 17, 203, 0.2);
      outline: none;
    }

    .input-error {
      border-color: #ff4757 !important;
      box-shadow: 0 0 0 2px rgba(255, 71, 87, 0.2) !important;
    }

    .error-message {
      color: #ff4757;
      font-size: 12px;
      margin-top: 5px;
      display: none;
    }

    .captcha-group {
      display: flex;
      gap: 10px;
    }

    .captcha-input {
      flex: 1;
    }

    .captcha-btn {
      padding: 0 20px;
      background: linear-gradient(to right, #6a11cb, #2575fc);
      color: white;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.3s;
      white-space: nowrap;
    }

    .captcha-btn:hover {
      opacity: 0.9;
    }

    .captcha-btn:disabled {
      background: #ccc;
      cursor: not-allowed;
    }

    .terms {
      display: flex;
      align-items: flex-start;
      margin-bottom: 25px;
      font-size: 14px;
    }

    .terms input {
      margin-right: 10px;
      margin-top: 3px;
    }

    .terms a {
      color: #6a11cb;
      text-decoration: none;
    }

    .terms a:hover {
      text-decoration: underline;
    }

    .register-btn {
      width: 100%;
      padding: 14px;
      background: linear-gradient(to right, #6a11cb, #2575fc);
      color: white;
      border: none;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: transform 0.2s, box-shadow 0.2s;
      margin-bottom: 25px;
    }

    .register-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(106, 17, 203, 0.4);
    }

    .register-btn:active {
      transform: translateY(0);
    }

    .login-link {
      text-align: center;
      color: #666;
      font-size: 14px;
    }

    .login-link a {
      color: #6a11cb;
      text-decoration: none;
      font-weight: 500;
      transition: color 0.2s;
    }

    .login-link a:hover {
      color: #2575fc;
      text-decoration: underline;
    }

    @media (max-width: 480px) {
      .register-container {
        padding: 30px 25px;
      }

      h1 {
        font-size: 24px;
      }

      .captcha-group {
        flex-direction: column;
      }

      .captcha-btn {
        padding: 12px;
        margin-top: 10px;
      }
    }

    .success-message {
      display: none;
      background-color: #2ed573;
      color: white;
      padding: 12px;
      border-radius: 8px;
      text-align: center;
      margin-bottom: 20px;
    }
  </style>
</head>
<body>
<div class="register-container">
  <h1>用户注册</h1>

  <div class="success-message" id="successMessage">
    注册成功！正在跳转到登录页面...
  </div>

  <form id="registerForm" action="/api/user/register" method="post" enctype="multipart/form-data">

    <div class="input-group">
      <label for="username">用户名</label>
      <input type="text" id="username" name="username" placeholder="请输入用户名" required>
      <div class="error-message" id="usernameError">用户名不能为空</div>
    </div>

    <div class="input-group">
      <label for="email">邮箱号</label>
      <input type="email" id="email" name="email" placeholder="请输入您的邮箱" required>
      <div class="error-message" id="emailError">请输入有效的邮箱地址</div>
    </div>

    <div class="input-group">
      <label for="password">密码</label>
      <input type="password" id="password" name="password" placeholder="请输入密码" required>
      <div class="error-message" id="passwordError">密码长度至少8位，包含字母和数字</div>
    </div>

    <div class="input-group">
      <label for="confirmPassword">确认密码</label>
      <input type="password" id="confirmPassword" name="confirmPassword" placeholder="请再次输入密码" required>
      <div class="error-message" id="confirmPasswordError">两次输入的密码不一致</div>
    </div>

    <div class="input-group">
      <label for="captcha">验证码</label>
      <div class="captcha-group">
        <input type="text" id="captcha" name="captcha" class="captcha-input" placeholder="请输入验证码" required>
        <button type="button" class="captcha-btn" id="getCaptcha">获取验证码</button>
      </div>
      <div class="error-message" id="captchaError">请输入正确的验证码</div>
    </div>

    <button type="submit" class="register-btn">注册</button>
  </form>

  <div class="login-link">
    已有账号？<a href="/login">立即登录</a>
  </div>
</div>

<script>
  // 获取DOM元素（与注册页面HTML元素ID严格对应）
  const registerForm = document.getElementById('registerForm');
  const emailInput = document.getElementById('email');
  const usernameInput = document.getElementById('username');
  const passwordInput = document.getElementById('password');
  const confirmPasswordInput = document.getElementById('confirmPassword');
  const captchaInput = document.getElementById('captcha');
  const getCaptchaBtn = document.getElementById('getCaptcha');
  const successMessage = document.getElementById('successMessage');

  // 验证正则规则（与后端逻辑保持一致）
  const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // 邮箱格式
  const PASSWORD_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/; // 密码：8位+字母+数字
  const USERNAME_REGEX = /^.{2,20}$/; // 用户名：2-20位字符（可按需调整）

  /**
   * 显示错误信息（复用注册页样式，与输入框ID关联）
   * @param {HTMLElement} inputElement - 输入框元素
   * @param {string} message - 错误提示内容
   */
  function showError(inputElement, message) {
    const errorElement = document.getElementById(inputElement.id + 'Error');
    inputElement.classList.add('input-error');
    errorElement.textContent = message;
    errorElement.style.display = 'block';
  }

  /**
   * 清除错误信息
   * @param {HTMLElement} inputElement - 输入框元素
   */
  function clearError(inputElement) {
    const errorElement = document.getElementById(inputElement.id + 'Error');
    inputElement.classList.remove('input-error');
    errorElement.style.display = 'none';
  }

  /**
   * 验证单个输入字段（适配所有表单字段，与后端校验逻辑对齐）
   * @param {HTMLElement} inputElement - 输入框元素
   * @returns {boolean} - 验证结果（true为通过）
   */
  function validateField(inputElement) {
    const value = inputElement.value.trim();

    // 通用非空验证
    if (!value) {
      showError(inputElement, '此字段不能为空');
      return false;
    }

    // 按字段类型/ID差异化验证
    switch (inputElement.id) {
      case 'username':
        // 用户名长度验证（2-20位）
        if (!USERNAME_REGEX.test(value)) {
          showError(inputElement, '用户名长度需为2-20位');
          return false;
        }
        break;
      case 'email':
        // 邮箱格式验证
        if (!EMAIL_REGEX.test(value)) {
          showError(inputElement, '请输入有效的邮箱地址');
          return false;
        }
        break;
      case 'password':
        // 密码强度验证（与后端密码规则保持一致）
        if (!PASSWORD_REGEX.test(value)) {
          showError(inputElement, '密码长度至少8位，包含字母和数字');
          return false;
        }
        break;
      case 'confirmPassword':
        // 确认密码与原密码一致性验证
        const password = passwordInput.value.trim();
        if (value !== password) {
          showError(inputElement, '两次输入的密码不一致');
          return false;
        }
        break;
      case 'captcha':
        // 验证码非空及长度验证（假设验证码为6位，可按需调整）
        if (value.length !== 6) {
          showError(inputElement, '验证码需为6位字符');
          return false;
        }
        break;
    }

    clearError(inputElement);
    return true;
  }

  /**
   * 发送注册验证码（对接后端 /sendRegisterCode 接口）
   * @param {string} email - 目标邮箱
   * @returns {Promise<Object>} - 接口响应结果（success: boolean, message: string）
   */
  async function sendRegisterCode(email) {
    try {
      const response = await fetch('/spi/verification/sendRegisterCode', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          email: email // 与后端接口参数名一致
        })
      });

      const result = await response.json();
      return result; // 后端返回格式：{success: true/false, message: "提示信息"}
    } catch (error) {
      console.error('发送验证码失败:', error);
      return { success: false, message: '网络异常，请稍后重试' };
    }
  }/**
   * 发送注册验证码（对接新的后端接口）
   * @param {string} email - 目标邮箱
   * @returns {Promise<Object>} - 接口响应结果
   */
  async function sendRegisterCode(email) {
    try {
      const response = await fetch('/api/verification/send', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          email: email,
          type: '1' // 注册类型，对应后端的Byte类型1
        })
      });

      const result = await response.json();
      return result; // 后端返回格式：{success: true/false, message: "提示信息"}
    } catch (error) {
      console.error('发送验证码失败:', error);
      return { success: false, message: '网络异常，请稍后重试' };
    }
  }

  /**
   * 验证注册验证码（对接新的后端接口）
   * @param {string} email - 目标邮箱
   * @param {string} code - 用户输入的验证码
   * @returns {Promise<boolean>} - 验证结果（true为通过）
   */
  async function verifyRegisterCode(email, code) {
    try {
      const response = await fetch('/api/verification/verify', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          email: email,
          code: code,
          type: '1' // 注册类型验证码，与后端定义的 (byte)1 一致
        })
      });

      const result = await response.json();
      if (!result.success) {
        // 验证码错误时，显示后端返回的提示
        showError(captchaInput, result.message);
        return false;
      }
      return true;
    } catch (error) {
      console.error('验证验证码失败:', error);
      showError(captchaInput, '网络异常，验证失败');
      return false;
    }
  }
  /**
   * 提交注册表单（对接新的后端接口）
   * @param {FormData} formData - 表单数据
   * @returns {Promise<Object>} - 接口响应结果
   */
  async function submitRegisterForm(formData) {
    try {
      const response = await fetch('/api/user/register', {
        method: 'POST',
        body: formData
      });

      const result = await response.json();
      return result; // 后端返回格式：{success: true/false, message: "注册结果提示", data: 用户信息}
    } catch (error) {
      console.error('注册请求失败:', error);
      return { success: false, message: '网络异常，注册失败' };
    }
  }

  /**
   * 验证码倒计时功能（防止重复发送）
   * @param {HTMLButtonElement} button - 验证码按钮元素
   * @param {number} countdownSeconds - 倒计时秒数（默认60秒）
   */
  function startCountdown(button, countdownSeconds = 60) {
    let countdown = countdownSeconds;
    button.disabled = true;
    button.textContent = `重新发送(${countdown}s)`;

    const timer = setInterval(() => {
      countdown--;
      button.textContent = `重新发送(${countdown}s)`;

      if (countdown <= 0) {
        clearInterval(timer);
        button.disabled = false;
        button.textContent = '获取验证码';
      }
    }, 1000);
  }

  // 2. 输入框实时验证（失焦时校验，输入时清除错误）
  document.querySelectorAll('#username, #email, #password, #confirmPassword, #captcha').forEach(input => {
    input.addEventListener('blur', () => validateField(input));
    input.addEventListener('input', () => clearError(input));
  });

  // 3. 「获取验证码」按钮点击事件（对接发送验证码接口）
  getCaptchaBtn.addEventListener('click', async function () {
    const email = emailInput.value.trim();
    const button = this;

    // 先验证邮箱格式
    if (!validateField(emailInput)) {
      return;
    }

    // 禁用按钮，防止重复点击
    button.disabled = true;
    button.textContent = '发送中...';

    // 调用发送验证码接口
    const sendResult = await sendRegisterCode(email);

    if (sendResult.success) {
      // 发送成功：启动倒计时，提示用户
      alert(sendResult.message);
      startCountdown(button);
    } else {
      // 发送失败：恢复按钮，显示错误
      alert(sendResult.message); // 如“该邮箱已注册”
      button.disabled = false;
      button.textContent = '获取验证码';
    }
  });

  // 4. 注册表单提交事件
  registerForm.addEventListener('submit', async function (e) {
    e.preventDefault();

    // 步骤1：验证所有表单字段
    const formFields = [usernameInput, emailInput, passwordInput, confirmPasswordInput, captchaInput];
    let isFormValid = true;

    formFields.forEach(field => {
      if (!validateField(field)) {
        isFormValid = false;
      }
    });


    // 验证不通过，终止提交
    if (!isFormValid) {
      return;
    }

    // 步骤3：验证验证码
    const email = emailInput.value.trim();
    const captcha = captchaInput.value.trim();
    const isCodeValid = await verifyRegisterCode(email, captcha);

    if (!isCodeValid) {
      return;
    }

    // 步骤4：准备表单数据（适配新的后端接口参数）
    const formData = new FormData();

    // 添加必填字段
    formData.append('email', email);
    formData.append('username', usernameInput.value.trim());
    formData.append('password', passwordInput.value.trim());


    // 步骤5：禁用注册按钮
    const registerBtn = this.querySelector('.register-btn');
    registerBtn.disabled = true;
    registerBtn.textContent = '注册中...';

    // 步骤6：提交注册请求
    const registerResult = await submitRegisterForm(formData);

    // 步骤7：处理注册结果
    if (registerResult.success) {
      successMessage.style.display = 'block';
      registerForm.style.display = 'none';

      setTimeout(() => {
        window.location.href = '/login';
      }, 2000);
    } else {
      alert(registerResult.message); // 显示后端返回的错误信息
      registerBtn.disabled = false;
      registerBtn.textContent = '注册';
    }
  });
</script>
</body>
</html>